package hse.jack.filter;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import javax.security.auth.login.AccountException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.nutz.mvc.annotation.Chain;

/**
 * 
 * @author jack
 * @version 1.0
 * @date 二〇一三年三月七日 10:52:02
 * 
 */
public class PriviledgeFilter implements Filter {
	private Properties pp = new Properties();

	@Override
	public void destroy() {
		pp = null;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		// 访问路径
		String requestURI = request.getRequestURI().replace(
				request.getContextPath() + "/", "");
		String action = req.getParameter("action");
		// 获取Action参数,例如：add
		action = action == null ? "" : action;
		// 拼接成URI
		String uri = requestURI + "?action=" + action;
		String role = (String) request.getSession(true).getAttribute("role");
		role = role == null ? "guest" : role; // 默认为Guest

		boolean authentificated = false;
		// 检查用户角色权限是否有访问权限该uri
		for (Object obj : pp.keySet()) {
			String key = (String) obj;
			// 使用正则表达式验证需要将？替换一下，并将通配符*处理一下
			if (uri.matches(key.replace("?", "\\?").replace(".", "\\.")
					.replace("*", ".*"))) {
				if (role.equals(pp.get(key))) {
					authentificated = true;
					break;
				}
			}
		}
		if (!authentificated) {
			throw new RuntimeException(new AccountException("您无权限访问！！"));
		}
		chain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String file = config.getInitParameter("file");
		String realPath = config.getServletContext().getRealPath(file);
		try {
			pp.load(new FileInputStream(realPath));
		} catch (Exception e) {
			config.getServletContext().log("读取权限控制文件失败！", e);
			// 加载失败
		}

	}

}
